<template>
  <n-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-placement="left"
    label-width="auto"
    require-mark-placement="right-hanging"
    :disabled="isSubmitting"
    class="py-4"
  >
    <n-grid :cols="2" :x-gap="24">
      <n-form-item-grid-item label="单位名称" path="name">
        <n-input v-model:value="formData.name" placeholder="请输入单位全称" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="单位简称" path="shortName">
        <n-input v-model:value="formData.shortName" placeholder="请输入单位简称" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="校准编号" path="calibrationCode">
        <n-input v-model:value="formData.calibrationCode" placeholder="请输入校准编号" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="收件编号" path="receiptCode">
        <n-input v-model:value="formData.receiptCode" placeholder="请输入收件编号" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="单位类型" path="unitType">
        <n-select
          v-model:value="formData.unitType"
          placeholder="请选择单位类型"
          :options="unitTypeOptions"
          filterable
        />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="单位级别" path="unitLevel">
        <n-select
          v-model:value="formData.unitLevel"
          placeholder="请选择单位级别"
          :options="unitLevelOptions"
          filterable
        />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="单位联系人" path="contactPerson">
        <n-input v-model:value="formData.contactPerson" placeholder="请输入单位联系人" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="座机" path="landlinePhone">
        <n-input v-model:value="formData.landlinePhone" placeholder="请输入座机号码" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="手机" path="mobilePhone">
        <n-input v-model:value="formData.mobilePhone" placeholder="请输入手机号码" />
      </n-form-item-grid-item>
      <n-form-item-grid-item :span="2" label="备注" path="remarks">
        <n-input
          v-model:value="formData.remarks"
          type="textarea"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </n-form-item-grid-item>
    </n-grid>

    <div class="flex justify-between mt-6">
      <div>
        <n-button v-if="!initialData" @click="generateMockData" type="info" ghost>
          🎲 一键生成虚拟信息
        </n-button>
      </div>
      <div>
        <n-button @click="handleCancel" :disabled="isSubmitting" class="mr-4">取消</n-button>
        <n-button type="primary" @click="handleSubmit" :loading="isSubmitting" :disabled="isSubmitting">
          {{ initialData ? '保存更新' : '创建' }}
        </n-button>
      </div>
    </div>
  </n-form>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, onMounted } from 'vue';
import {
  NForm,
  NFormItem,
  NFormItemGridItem,
  NInput,
  NSelect,
  NButton,
  NGrid,
  useMessage
} from 'naive-ui';
import { unitTypeOptions, unitLevelOptions } from '@/utils/constants';

const props = defineProps({
  initialData: {
    type: Object,
    default: null,
  },
});

const emits = defineEmits(['submit', 'cancel']);

const message = useMessage();
const formRef = ref(null);
const defaultFormValues = {
  id: null,
  name: '',
  shortName: '',
  calibrationCode: '',
  receiptCode: '',
  unitType: null,
  unitLevel: null,
  contactPerson: '',
  landlinePhone: '',
  mobilePhone: '',
  remarks: '',
};
const formData = ref({ ...defaultFormValues });
const isSubmitting = ref(false);

const rules = {
  name: { required: true, message: '请输入单位名称', trigger: ['input', 'blur'] },
  shortName: { required: true, message: '请输入单位简称', trigger: ['input', 'blur'] },
  calibrationCode: { required: true, message: '请输入标定代码', trigger: ['input', 'blur'] },
  receiptCode: { required: true, message: '请输入回执代码', trigger: ['input', 'blur'] },
  unitType: { required: true, message: '请选择单位类型', trigger: 'change' },
  unitLevel: { required: true, message: '请选择单位级别', trigger: 'change' },
  contactPerson: { required: true, message: '请输入联系人姓名', trigger: ['input', 'blur'] },
  landlinePhone: {
    pattern: /^(\d{3,4}-?)?\d{7,8}$/,
    message: '请输入正确的座机电话格式',
    trigger: ['input', 'blur']
  },
  mobilePhone: {
    pattern: /^1[3-9]\d{9}$/,
    message: '请输入正确的手机号码',
    trigger: ['input', 'blur']
  },
};

watch(() => props.initialData, (newData) => {
  if (newData) {
    formData.value = { ...defaultFormValues, ...newData };
  } else {
    formData.value = { ...defaultFormValues };
  }
}, { immediate: true, deep: true });


const handleSubmit = async (e) => {
  if (isSubmitting.value) return; // 防止重复提交

  e.preventDefault();
  try {
    isSubmitting.value = true;
    await new Promise((resolve, reject) => {
      formRef.value?.validate((errors) => {
        if (!errors) {
          resolve();
        } else {
          reject(new Error('表单验证失败'));
        }
      });
    });

    await emits('submit', { ...formData.value });
  } catch (error) {
    console.error('表单提交失败:', error);
    message.error('请检查表单填写是否正确');
  } finally {
    isSubmitting.value = false;
  }
};

const handleCancel = () => {
  emits('cancel');
};

const resetForm = () => {
  formData.value = { ...defaultFormValues };
  formRef.value?.restoreValidation();
};

defineExpose({
  resetForm,
});

// 生成虚拟数据的函数
const generateMockData = () => {
  const unitNames = [
    '中共中央组织部', '教育部', '财政部', '人力资源和社会保障部', '国家发展和改革委员会',
    '工业和信息化部', '公安部', '民政部', '司法部', '生态环境部',
    '住房和城乡建设部', '交通运输部', '水利部', '农业农村部', '商务部'
  ];

  const shortNames = [
    '中组部', '教育部', '财政部', '人社部', '发改委',
    '工信部', '公安部', '民政部', '司法部', '生态环境部',
    '住建部', '交通部', '水利部', '农业部', '商务部'
  ];

  const contactPersons = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
  const unitTypes = unitTypeOptions.map(opt => opt.value);
  const unitLevels = unitLevelOptions.map(opt => opt.value);

  const randomIndex = Math.floor(Math.random() * unitNames.length);
  const randomContactIndex = Math.floor(Math.random() * contactPersons.length);

  // 生成随机电话号码
  const generateLandline = () => {
    const areaCode = '010';
    const number = Math.floor(Math.random() * 90000000) + 10000000;
    return `${areaCode}-${number}`;
  };

  const generateMobile = () => {
    const prefixes = ['138', '139', '150', '151', '152', '158', '159', '188', '189'];
    const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
    const suffix = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
    return prefix + suffix;
  };

  // 填充表单数据
  formData.value = {
    ...defaultFormValues,
    name: unitNames[randomIndex],
    shortName: shortNames[randomIndex],
    calibrationCode: `${shortNames[randomIndex].toUpperCase()}${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`,
    receiptCode: `R${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`,
    unitType: unitTypes[Math.floor(Math.random() * unitTypes.length)],
    unitLevel: unitLevels[Math.floor(Math.random() * unitLevels.length)],
    contactPerson: contactPersons[randomContactIndex],
    landlinePhone: generateLandline(),
    mobilePhone: generateMobile(),
    remarks: `这是${unitNames[randomIndex]}的虚拟测试数据`,
  };


};

onMounted(() => {
  if (props.initialData) {
    formData.value = { ...defaultFormValues, ...props.initialData };
  }
});

</script>